package com.example.administrator.newxlmedical;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Environment;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.Toast;

import com.example.administrator.baseproject.BaseActivity;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import adapters.CommonStateErrorAdapter;
import beans.GoodsDetailsBean;
import beans.NewUserInfoBean;
import beans.OperateGoodsDetailsBean;
import beans.RfidListBean;
import beans.TimeoutBean;
import beans.UnusedGoodsBean;
import butterknife.BindView;
import butterknife.OnClick;
import constants.Constants;
import constants.HandlerConstant;
import customhandler.MyHandler;
import dialogs.OpenDoorAfterOperationDialog;
import dialogs.SignOutDialog;
import fragments.ReturnErrorFragment;
import fragments.ReturnFragment;
import fragments.TakeErrorFragment;
import fragments.TakeFragment;
import netframe.GetRetrofit;
import netframe.MyAction1;
import netframe.NetAddress;
import netframe.NetReconnectFunc1;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import rx.Emitter;
import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.schedulers.Schedulers;
import singleton.SingletonClass;
import utils.ActivityControl;
import utils.ActivityUtil;
import utils.CustomSharedPreferencePath;
import utils.FormateUtils;
import utils.LoginRedCountUtils;
import utils.MediaPlayerUtils;
import utils.ObjectSaveUtil;
import utils.TimeUtil;
import utils.ToastUtil;


public class TakeAndReturnActivity extends BaseActivity implements TakeErrorFragment.TakeErrorInterface, TakeFragment.TakeInterface, ReturnErrorFragment.ReturnErrorInterface, ReturnFragment.ReturnInterface {

    @BindView(R.id.iv_common_toolbar_home)
    ImageView ivHome;
    //    @BindView(R.id.iv_common_toolbar_return)
//    ImageView ivReturn;
    @BindView(R.id.fl_take_return_container)
    FrameLayout flEmpty;

    private MediaPlayer mediaPlayer;
    private int selectCabinet = 0;

    private NewUserInfoBean.DataBean userInfoBean;

    private CommonStateErrorAdapter errorAdapter;
    private List<OperateGoodsDetailsBean.DataBean> takeList = new ArrayList<>();
    private List<OperateGoodsDetailsBean.DataBean> returnList = new ArrayList<>();
    private List<OperateGoodsDetailsBean.DataBean> takeErrorList = new ArrayList<>();
    private List<OperateGoodsDetailsBean.DataBean> returnErrorList = new ArrayList<>();

    private List<OperateGoodsDetailsBean.DataBean> errorGoodsList = new ArrayList<>();
    //用于判断取出和放回是否都完成
    private int count;
    private int takeCount, returnCount, takeErrorCount, returnErrorCount;
    private ReturnFragment returnFragment;
    private TakeErrorFragment takeErrorFragment;
    private ReturnErrorFragment returnErrorFragment;
    private TakeFragment takeFragment;
    private MyHandler allHandler;
    private StringBuilder sb = new StringBuilder();
    private Map<Integer, String> hashMap;
    private Map<String, OperateGoodsDetailsBean.DataBean> errorMap = new HashMap<>();
    private boolean isLoadingTask = false;
    private boolean isTimeOut;
    private int size;
    private int num;
    private long star;
    private int temp;
    private DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");
    private String s;
    private int style;
    private SharedPreferences sharedPreferences;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_take_and_return);
    }

    @Override
    public void initView() {
        super.initView();
        ivHome.setClickable(false);
        Map<String, OperateGoodsDetailsBean.DataBean> recordList = (Map<String, OperateGoodsDetailsBean.DataBean>) CustomSharedPreferencePath.getData(this, Constants.RECORD_ERROR_GOODS, null);

        if (recordList != null) {
            errorMap = recordList;
        }
        sharedPreferences = ActivityUtil.getSharedPreferences(this);
        allHandler = SingletonClass.getSingleton(MyHandler.class);
        selectCabinet = getIntent().getIntExtra(Constants.TAKE_AND_RETURN_ACTIVITY, 0);

        MediaPlayerUtils.playSound(this,R.raw.sure_sound);
        userInfoBean = (NewUserInfoBean.DataBean) ObjectSaveUtil.readObject(this, Constants.USER_INFO_BEAN, Constants.USER_INFO_BEAN);

        Object o = ObjectSaveUtil.readObject(this, Constants.CABINETINFO_LOGICNUMBER_HASHMAP, Constants.CABINETINFO_LOGICNUMBER_HASHMAP);
        sb.delete(0, sb.length());
        if (o != null) {
            hashMap = (Map<Integer, String>) o;
            Set set = hashMap.entrySet();
            Iterator iterator = set.iterator();
            while (iterator.hasNext()) {
                Map.Entry mapentry = (Map.Entry) iterator.next();
                sb.append("'" + mapentry.getKey() + "',");
            }
            sb.deleteCharAt(sb.length() - 1);
        }

        showLoadingView(flEmpty);
        allHandler.sendEmptyMessageDelayed(HandlerConstant.TAKEANDRETURN_ERROR, 20000);
    }

    @OnClick({R.id.iv_common_toolbar_home})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_common_toolbar_home:
                finish();
                break;
//            case R.id.iv_common_toolbar_return:
//                finish();
//                break;
        }
    }

    @Override
    protected void onHandleMessage(Message msg) {
        super.onHandleMessage(msg);
        switch (msg.what) {
            case HandlerConstant.SCAN_COMPLETE:
                star = System.currentTimeMillis();
                Log.e(TAG, "SCAN_COMPLETE");
                allHandler.removeMessages(HandlerConstant.TAKEANDRETURN_ERROR);
                scanComplete(msg);
                break;
            case HandlerConstant.SCAN_COMPLETE_ERROR:
                ivHome.setClickable(true);
                allHandler.removeMessages(HandlerConstant.TAKEANDRETURN_ERROR);
                Log.e(TAG, "SCAN_COMPLETE_ERROR");
                finish();
                break;
            case HandlerConstant.FINISH_NETWORK:
                count++;
                if (count == 2) {
                    num = takeCount + returnCount + takeErrorCount + returnErrorCount;
                    if (num != 0) {
                        saveToFile("RfidCode: " + s);
                        saveToFile("RfidSize: " + size + "--------Count: " + num);
                        StringBuilder takeErrorSb = new StringBuilder();
                        if (takeErrorList.size() != 0){
                            for (OperateGoodsDetailsBean.DataBean dataBean : takeErrorList) {
                                takeErrorSb.append(dataBean.getRfidCode());
                            }
                        }
                        saveToFile("takeErrorRFID : " + takeErrorSb.toString() + "   count : " + takeErrorList.size());
                        StringBuilder returnErrorSb = new StringBuilder();
                        if (returnErrorList.size() != 0){
                            for (OperateGoodsDetailsBean.DataBean dataBean : returnErrorList) {
                                returnErrorSb.append(dataBean.getRfidCode());
                            }
                        }

                        saveToFile("returnErrorRFID : " + returnErrorSb.toString() + "   count : " + returnErrorList.size());
                        saveToFile("-------------------------------------------------------------------------" );

                        allHandler.removeMessages(HandlerConstant.TAKEANDRETURN_REFRESH);
                        count = 0;
                        String id ;
                        if (userInfoBean.getRoleInfoId() != 1 && userInfoBean.getRoleInfoId() != 4){
                            id = "0";
                        }else {
                            id = userInfoBean.getID()+"";
                        }

                        hideLoadingView();
                        initFragment();

                        LoginRedCountUtils.getLoginDataCount(TakeAndReturnActivity.this,id,NetAddress.deptCode,false);
//                        new LoginRedCountUtils().getRedDotCount(TakeAndReturnActivity.this);
                    }
                    ivHome.setClickable(true);
                    allHandler.sendEmptyMessage(HandlerConstant.ERROR_MODIFY);
                }
                break;

            case HandlerConstant.TAKEANDRETURN_REFRESH:
                ivHome.setClickable(true);
                saveToFile("RfidCode: " + s);
                saveToFile("RfidSize: " + size + "--------Count: " + num);
                ToastUtil.showToast(TakeAndReturnActivity.this, "未查询到物品信息");
                finish();
                break;
            case HandlerConstant.TAKEANDRETURN_ERROR:
                ivHome.setClickable(true);
                saveToFile("RfidCode: " + s);
                saveToFile("RfidSize: " + size + "--------Count: " + num);
                ToastUtil.showToast(TakeAndReturnActivity.this, "设备异常!");
                finish();
                break;
        }
    }

    private void scanComplete(Message msg) {
        int zengliang = 0;
        int jianliang = 0;
        s = (String) msg.obj;
        String[] split = s.split(Constants.INCREASE_DECREASE_SPLIT);
        Log.e(TAG, "scanComplete:   " + s);
        if (split.length >= 1) {
            if (!TextUtils.isEmpty(split[0])) {
                Log.e(TAG, "归还: ");
                //根据RFIDCODE从服务器获取归还(即单片机增加的)的相关信息
                ArrayList<String> returns = FormateUtils.getRfidCodes(split[0]);
                size += returns.size();
                zengliang = returns.size();
                style = 2;
                operateGoodsDetails(returns, String.valueOf(selectCabinet), 3, style);
            } else {
                Log.e(TAG, "归还: FINISH_NETWORK");
                sendEmptyMessage(HandlerConstant.FINISH_NETWORK);
            }
            if (split.length == 2) {
                if (!TextUtils.isEmpty(split[1])) {
                    Log.e(TAG, "取出: ");
                    //根据RFIDCODE从服务器获取取出(即单片机减少的)的相关信息
                    ArrayList<String> takes = FormateUtils.getRfidCodes(split[1]);
                    size += takes.size();
                    jianliang = takes.size();
                    style = 1;
                    operateGoodsDetails(takes, String.valueOf(selectCabinet), 4, style);
                } else {
                    Log.e(TAG, "取出: FINISH_NETWORK");
                    sendEmptyMessage(HandlerConstant.FINISH_NETWORK);
                }
            } else {
                Log.e(TAG, "length: FINISH_NETWORK");
                sendEmptyMessage(HandlerConstant.FINISH_NETWORK);
            }
        } else {
            //没有做取出,放入的操作,可做提醒之类的
            hideLoadingView();
            finish();
        }
        if (Constants.CHECK_LOG) {
            Toast.makeText(this,"增量  " + zengliang + "   减量  " + jianliang,Toast.LENGTH_SHORT).show();
        }
    }

    private void initFragment() {
        takeFragment = new TakeFragment();
        returnFragment = new ReturnFragment();
        takeErrorFragment = new TakeErrorFragment();
        returnErrorFragment = new ReturnErrorFragment();

        Bundle takeBundle = new Bundle();
        takeBundle.putString("count", takeCount + "");
        RfidListBean bean = new RfidListBean();
        bean.setList(takeList);
        takeBundle.putSerializable(Constants.TAKE_FRAGMENT, bean);
        takeFragment.setArguments(takeBundle);

        Bundle returnBundle = new Bundle();
        returnBundle.putString("count", returnCount + "");
        RfidListBean returnBean = new RfidListBean();
        returnBean.setList(returnList);
        returnBundle.putSerializable(Constants.RETURN_FRAGMENT, returnBean);
        returnFragment.setArguments(returnBundle);

        Bundle takeErrorBundle = new Bundle();
        takeErrorBundle.putString("count", takeErrorCount + "");
        RfidListBean takeErrorBean = new RfidListBean();
        takeErrorBean.setList(takeErrorList);
        takeErrorBundle.putSerializable(Constants.TAKE_ERROR_FRAGMENT, takeErrorBean);
        takeErrorFragment.setArguments(takeErrorBundle);

        Bundle returnErrorBundle = new Bundle();
        returnErrorBundle.putString("count", returnErrorCount + "");
        RfidListBean returnErrorBean = new RfidListBean();
        returnErrorBean.setList(returnErrorList);
        returnErrorBundle.putSerializable(Constants.RETURN_ERROR_FRAGMENT, returnErrorBean);
        returnErrorFragment.setArguments(returnErrorBundle);

        if (takeErrorList.size() != 0) {
            selectFragment(takeErrorFragment);
        } else if (returnErrorList.size() != 0) {
            selectFragment(returnErrorFragment);
        } else if (takeList.size() != 0) {
            selectFragment(takeFragment);
        } else if (returnList.size() != 0) {
            selectFragment(returnFragment);
        }
    }

    private void selectFragment(Fragment fragment) {
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        transaction.replace(R.id.fl_take_return_container, fragment);
        transaction.commit();
    }

    //style:1取出   2放入
    private void operateGoodsDetails(final ArrayList<String> rfidList, final String cabinetCode, final int type, final int style) {
        GetRetrofit.getInstance().operateGoodDetails(NetAddress.token, NetAddress.machineCode, rfidList, NetAddress.terminalInfoId, cabinetCode, userInfoBean.getID(), type)
                .subscribeOn(Schedulers.io())
                .retryWhen(new NetReconnectFunc1())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<OperateGoodsDetailsBean>() {
                    @Override
                    public void call(OperateGoodsDetailsBean operateGoodsDetailsBean) {
                        errorGoodsList.clear();
                        int dataSize = 0;
                        int aberrantSize = 0;
                        List<OperateGoodsDetailsBean.DataBean> dataBean = operateGoodsDetailsBean.getData();
                        List<OperateGoodsDetailsBean.DataBean> aberrantData = operateGoodsDetailsBean.getAberrantData();
                        if (dataBean != null && dataBean.size() > 0) {
                            if (style == 1) {
                                takeCount = dataBean.size();
                                dataSize = dataBean.size();
                                takeList = FormateUtils.getDistinctList(dataBean, selectCabinet);
                            } else {
                                dataSize = dataBean.size();
                                returnCount = dataBean.size();
                                returnList = FormateUtils.getDistinctList(dataBean, selectCabinet);
                            }
                        }
                        if (aberrantData != null && aberrantData.size() > 0) {
                            errorGoodsList.addAll(aberrantData);
                            if (style == 1) {
                                aberrantSize = aberrantData.size();
                                takeErrorCount = aberrantData.size();
                                takeErrorList = FormateUtils.getDistinctList(aberrantData, selectCabinet);
                                deleteErrorGoods();
                            } else {
                                aberrantSize = aberrantData.size();
                                returnErrorCount = aberrantData.size();
                                returnErrorList = FormateUtils.getDistinctList(aberrantData, selectCabinet);
                                addErrorGoods();
                            }
                        }

                        sendEmptyMessage(HandlerConstant.FINISH_NETWORK);

                        if (dataSize != 0 || aberrantSize != 0) {
                        } else {
                            allHandler.sendEmptyMessageDelayed(HandlerConstant.TAKEANDRETURN_REFRESH, 3000);
                        }

                    }

                }, new MyAction1() {
                    @Override
                    public void call(Throwable throwable) {
                        super.call(throwable);
                        finish();
                        hideLoadingView();
                        showEmptyView(flEmpty);
                        Log.e(TAG, "call: " + throwable.getMessage());
                        ToastUtil.showToast(TakeAndReturnActivity.this, throwable.getMessage());
                    }
                });
    }

    private void addErrorGoods() {

        List<OperateGoodsDetailsBean.DataBean> list = new ArrayList<>();
        list.addAll(errorGoodsList);

        for (int i = 0; i < list.size(); i++) {
            OperateGoodsDetailsBean.DataBean dataBean = list.get(i);
            dataBean.setSelectCabinet(selectCabinet+"");
            dataBean.setErrorRecordTime(TimeUtil.getMillisecondDate());
            if (dataBean.getStatus() != 3) {
                String key = dataBean.getGID() + dataBean.getSpecification() + dataBean.getManufacturer() + dataBean.getStatus();
                String millisecondDate = TimeUtil.getMillisecondDate();
                if (errorMap.get(key) != null) {
                    OperateGoodsDetailsBean.DataBean bean = errorMap.get(key);
                    bean.setNumber(bean.getNumber() + 1);

                    bean.getBarCodeList().add(dataBean.getBarCode() + Constants.INCREASE_DECREASE_SPLIT +millisecondDate );
                    bean.setErrorRecordTime(millisecondDate);
                    bean.setSelectCabinet(selectCabinet+"");
                    errorMap.put(key, bean);
                }else {
                    Log.e("EEEE", "else " +  TimeUtil.getMillisecondDate());
                    errorMap.put(key, dataBean);
                }
            }
        }

        CustomSharedPreferencePath.saveData(this, Constants.RECORD_ERROR_GOODS, errorMap);
    }

    private void deleteErrorGoods() {
        List<OperateGoodsDetailsBean.DataBean> list = new ArrayList<>();
        list.addAll(errorGoodsList);
        for (int i = 0; i < list.size(); i++) {
            OperateGoodsDetailsBean.DataBean dataBean = list.get(i);
            String key = dataBean.getGID() + dataBean.getSpecification() + dataBean.getManufacturer() + dataBean.getStatus();
            Log.e("test", "deleteErrorGoods " +  key );
            if (errorMap.get(key) != null) {
                OperateGoodsDetailsBean.DataBean bean = errorMap.get(key);
//                if (bean.getNumber() - 1 <= 0) {
//                    errorMap.remove(key);
//                } else {
                if (bean.getNumber() > 1) {
                    bean.setNumber(bean.getNumber() - 1);
                    int index = 0;
                    for (int i1 = 0; i1 < bean.getBarCodeList().size(); i1++) {
                        Log.e("test", "deleteErrorGoods: " + bean.getBarCodeList().get(i1).split(Constants.INCREASE_DECREASE_SPLIT)[0] );
                        if (bean.getBarCodeList().get(i1).split(Constants.INCREASE_DECREASE_SPLIT)[0].equals(dataBean.getBarCode())){
                            index = i1;
                        }
                    }
                    bean.getBarCodeList().remove(index);
                    errorMap.put(key, bean);
                }else {
                    Log.e("test", "remove: " + key );
                    errorMap.remove(key);
                }
            }
        }
        CustomSharedPreferencePath.saveData(this, Constants.RECORD_ERROR_GOODS, errorMap);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        MediaPlayerUtils.stop();
    }

    @Override
    public void takeErrorSure() {
        if (returnErrorList.size() != 0) {
            selectFragment(returnErrorFragment);
        } else if (takeList.size() != 0) {
            selectFragment(takeFragment);
        } else if (returnList.size() != 0) {
            selectFragment(returnFragment);
        } else {
            if (Constants.IS_FUYI) {
                showDialog();
            }else {
                ActivityUtil.jumpToActivity(this,MainActivity.class);
                finish();
            }
        }
    }

    @Override
    public void returnErrorSure() {
        if (takeList.size() != 0) {
            selectFragment(takeFragment);
        } else if (returnList.size() != 0) {
            selectFragment(returnFragment);
        } else {
            if (Constants.IS_FUYI) {
                showDialog();
            }else {
                ActivityUtil.jumpToActivity(this,MainActivity.class);
                finish();
            }
        }
    }

    @Override
    public void takeSure() {
        if (returnList.size() != 0) {
            selectFragment(returnFragment);
        } else {
            if (Constants.IS_FUYI) {
                showDialog();
            }else {
                ActivityUtil.jumpToActivity(this,MainActivity.class);
                finish();
            }
        }
    }

    @Override
    public void returnSure() {
        if (Constants.IS_FUYI) {
            showDialog();
        }else {
            ActivityUtil.jumpToActivity(this,MainActivity.class);
            finish();
        }
    }

    public void saveToFile(String receiveData) {
        StringBuffer sb = new StringBuffer();
        try {
            if (Environment.getExternalStorageState().equals(
                    Environment.MEDIA_MOUNTED)) {
                String time = formatter.format(new Date());
                sb.append(time);
                sb.append("  ----------:  ");
                sb.append(receiveData);
                sb.append("  ----------;  ");
                sb.append("\r\n");
                String fileName = TimeUtil.getYear() + "-" + (TimeUtil.getMonth() + 1) + "-" + TimeUtil.getDay() + ".log";
                String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/TakeReturnLog/";
                File dir = new File(path);
                if (!dir.exists()) {
                    dir.mkdirs();
                }
                FileOutputStream fos = new FileOutputStream(path + fileName, true);
                fos.write(sb.toString().getBytes());
                fos.flush();
                fos.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void showDialog(){

        final OpenDoorAfterOperationDialog signOutDialog = new OpenDoorAfterOperationDialog(this, R.style.dialog);
        signOutDialog.setOwnerActivity(this);
        signOutDialog.setOnClickListener(new OpenDoorAfterOperationDialog.OnClickListener() {
            @Override
            public void onClick(View v, Dialog dialog) {
                ActivityUtil.jumpToActivity(TakeAndReturnActivity.this,MainActivity.class);
                finish();
                signOutDialog.cancel();
            }
        });
        signOutDialog.show();
    }

}
